﻿//   Skype-Moodle-Sloodle WebIntercom
//   Links a Skype Chat with a Moodle Web Chat and SL/OS Public Chat
//
//   Copyright (C) 2009 Marco Bandiera
//
//   This program is free software: you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation, either version 3 of the License, or
//   (at your option) any later version.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using SKYPE4COMLib;

namespace Simple_Chat_Skype_Bot
{
    public partial class SkypeChatBotForm : Form
    {
    	IChat ichat;
    	string message = ""; // initialize message to empty string
    	string slsrv; // sloodle website e.g. "http://sloodle.it/moodle";
    	string slchatlnk = "/mod/sloodle/mod/chat-1.0/linker.php?"; // chat-1.0 "linker.php" path
    	string slctrlid; // sloodle controller ID
    	string slpwd; // sloodle prim password
    	string slmodid; // sloodle module ID
    	string sluuid; // sloodle BOT UUID
    	string slavname; // sloodle avatar name
    	string slsrvacclvl = "sloodleserveraccesslevel=0&"; // sloodle server access level
    	
    	HttpWebRequest req, req1;
    	HttpWebResponse resp, resp1;
    	string html;
    	string[] htmlprs;
    	
    	int num;
    	int riga=0;
    	int row;
    	int debug=0; // Initialize Debug OFF
    	int start=0; // Initialize Disconnected
    	
        public SkypeChatBotForm()
        {
            InitializeComponent();
        }

        SkypeClass skype;

        public void SkypeChatBotForm_Load(object sender, EventArgs e)
        {
            skype = new SkypeClass(); // New Skype Class
            
            if (skype.Client.IsRunning != true) // If Skype Client is not running, then start it
                skype.Client.Start(true, true); // Start Skype Client
            
            skype.MessageStatus += new _ISkypeEvents_MessageStatusEventHandler(skype_MessageStatus);
            
            if (skype.CurrentUserStatus == TUserStatus.cusOffline) // If Skype User is Offline, then put him online
                skype.ChangeUserStatus(TUserStatus.cusOnline); // Set Skype User Online
        }

        void skype_MessageStatus(ChatMessage pMessage, TChatMessageStatus Status)
        {
         	slsrv=txbServer.Text;
        	slctrlid="sloodlecontrollerid="+txbCID.Text+"&";
        	slpwd="sloodlepwd="+txbPwd.Text+"&";
        	slmodid="sloodlemoduleid="+txbMID.Text+"&";
        	slavname="sloodleavname="+txbObName.Text+"&";
        	sluuid="sloodleuuid="+txbObUUID.Text+"&";
        	
        	message = slsrv+slchatlnk;
    		message += slctrlid+slpwd+slmodid;
    		message += sluuid+slavname+slsrvacclvl;

    		if (((debug==1) | (pMessage.Chat.FriendlyName==txbChatName.Text)) & (Status==TChatMessageStatus.cmsReceived))
            {
    			  txbChatID.Text=pMessage.ChatName;
				  message += "message="+pMessage.FromDisplayName+": "+pMessage.Body;
				  if (debug==1)
				  {
				  	textbox.Text+="MESSAGE = "+message+"\r\n"+"CHAT FRIENDLY NAME = "+pMessage.Chat.FriendlyName+"\r\n";
				  }			 
				  req = (HttpWebRequest) WebRequest.Create(message);
				  resp = (HttpWebResponse) req.GetResponse();
				  resp.Close();
        	}
        }
			
     
        void btnQuitClick(object sender, EventArgs e)
        {
        	Close();
        }
 
        
        void Timer1Tick(object sender, EventArgs e)
        {
        	if (txbChatID.Text!="")
        	{
        	ichat = skype.get_Chat(txbChatID.Text);
        	slsrv=txbServer.Text;
        	slctrlid="sloodlecontrollerid="+txbCID.Text+"&";
        	slpwd="sloodlepwd="+txbPwd.Text+"&";
        	slmodid="sloodlemoduleid="+txbMID.Text;//attenzione non mettere la "&"
           	message ="";
        	message += slsrv;
    		message += slchatlnk;
    		message += slctrlid;    	
    		message += slpwd;
    		message += slmodid;
    		//Se si invia una richiesta di questo genere, riceviamo i messaggi da trattare
 			req1 = (HttpWebRequest) WebRequest.Create(message);
			resp1 = (HttpWebResponse) req1.GetResponse();
			html = new StreamReader(resp1.GetResponseStream(),Encoding.UTF8).ReadToEnd();
			if (debug==1)
				{
					textbox.Text+="HTML = "+html+"\r\n";
				}		
			resp1.Close();
			htmlprs=html.Split('|','\n');
			num = htmlprs.Length;
			string testo="";
			if (num > 2)
			{
				for (int i=2;i<num;i+=3)
				// Ciascuna terna di valori contiene: ID messaggio, nome, messaggio
				// nel caso di SL/OS o Skype il messaggio contiene già il nome utente
				// nel caso di chat web il nome deve essere visualizzato
				{
					row = Convert.ToInt16(htmlprs[i]);
					if (row > riga)
					{
						if (htmlprs[i+2].Substring(0,1) != "(")
						{
							testo += "(Web Chat) "+htmlprs[i+1]+": ";
						}
						testo += htmlprs[i+2]+"\r\n";
						riga = row;
						if (testo.Substring(11,txbObName.Text.Length) != txbObName.Text)
						{
							ichat.SendMessage(testo);
						}
					}
				}
				if (debug==1)
					{
						textbox.Text+="TESTO = "+testo+"\r\n";
					}		
			}}
        }
        
           
        void BtnDebugClick(object sender, EventArgs e)
        {
        	if (debug==0)
        	{
        		debug=1;
        		btnDebug.Text="Debug OFF";
        	}
        	else
        	{
        		debug=0;
        		btnDebug.Text="Debug ON";
        	}       	
        }
        
        void BtnStartClick(object sender, EventArgs e)
        {
			if (start==0)
        	{
        		start=1;
        		btnStart.Text="Disconnect";
        		timer1.Enabled=true;
        	}
        	else
        	{
        		start=0;
        		btnStart.Text="Connect";
        		timer1.Enabled=false;
        	}       
        } 
    }
}